package com.yl.chainStore.control.user

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.pojo.vo.user.UpdatePasswordVo
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*

/**
 * 基础（权限获取，登录）
 */
@RestController
@RequestMapping("sys/index")
open class IndexController(
    private val iCompanyUserService: ICompanyUserService,
    private val iCompanyDeptService: ICompanyDeptService
) : BaseCtrl() {

    @PostMapping("login")
    @Transactional
    open fun login(@RequestBody body: JSONObject): ResponseBody {
        val loginName = body.getString("loginName") ?: return returnError(ErrorCode.PARAM_EMPTY, "请输入用户名")
        val password = body.getString("password") ?: return returnError(ErrorCode.PARAM_EMPTY, "请输入密码")

        return iCompanyUserService.login(loginName, password)
    }

    @GetMapping("getMenuTree")
    @Transactional
    open fun getMenuTree(): ResponseBody {

        return returnSuccess(iCompanyUserService.getUserMenuTree(getContext().userId, getContext().subCompanyId))
    }


    /**
     * 获取自己的信息
     */
    @GetMapping("getSelfInfo")
    @Transactional
    open fun getSelfInfo(): ResponseBody {
//        val a = 1
//        if(a ==1){
//            return returnError(ErrorCode.LOGIN_TIME_OUT,"登录状态失效")
//        }
        val user =
            iCompanyUserService.getUser(getContext().userId) ?: return returnError(ErrorCode.LOGIN_TIME_OUT, "登录状态失效")
        val dept = iCompanyDeptService.getDept(getContext().subCompanyId) ?: return returnError(
            ErrorCode.LOGIN_TIME_OUT,
            "登录状态失效"
        )

        val map = mutableMapOf<String, Any>()
        map["userId"] = getContext().userId
        map["userName"] = user.realName
        map["deptId"] = dept.id
        map["deptName"] = dept.name
        val permCodes = iCompanyUserService.getCachePermissionsSet(
            getContext().companyId,
            getContext().userId,
            getContext().subCompanyId
        ) ?: mutableSetOf()
        map["permCode"] = permCodes
        return returnSuccess(map)
    }

    /**
     * 切换分院
     */
    @PostMapping("switchSubCompany/{subCompanyId}")
    @Transactional
    open fun switchSubCompany(@PathVariable subCompanyId: Long): ResponseBody {
        val switchSubCompany = iCompanyUserService.switchSubCompany(subCompanyId)
        if (switchSubCompany.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return switchSubCompany
    }

    @RequestMapping("ping")
    @Transactional
    open fun pingWeb(): ResponseBody {
        return returnSuccess("pang")
    }

    @RequestMapping("getSelfPermCode")
    @Transactional
    open fun getSelfPermCode(): ResponseBody {
        return returnSuccess(
            iCompanyUserService.getCachePermissionsSet(
                getContext().companyId,
                getContext().userId,
                getContext().subCompanyId
            )
        )
    }

    @PostMapping("test")
    open fun test(@RequestBody array: JSONArray): ResponseBody {

        println(array.toString())
        return returnSuccess()
    }

    /**
     * 修改自己的密码
     */
        @PostMapping("updateSelfPassword")
    @Transactional(rollbackFor = [Exception::class])
    open fun updateSelfPassword(@RequestBody vo: UpdatePasswordVo):ResponseBody{
        val updatePassword = iCompanyUserService.updatePassword(
            getContext().userId,
            vo.oldPassword,
            vo.newPassword
        )
        if(updatePassword.bodyIsError()){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return updatePassword
        }
        return returnSuccess()
    }


}
